// 商品流水页面混入
import { getMockProductFlowList, getMockProductFlowStats } from '@/pagesData/api/productFlow.js'

export default {
	data() {
		return {
			// 页面状态
			loading: false,
			refreshing: false,
			loadingMore: false,
			hasMore: true,
			
			// 日期筛选
			dateType: 'day', // 'day' | 'month'
			selectedDate: '',
			showDatePicker: false,
			
			// 搜索和筛选
			searchKeyword: '',
			
			// 分页参数
			currentPage: 1,
			pageSize: 20,
			
			// 数据列表
			flowList: [],
			displayList: [],
			
			// 统计数据
			stats: {
				totalRecords: 0,
				totalPurchase: 0,
				totalReturn: 0,
				netFlow: 0,
				todayRecords: 0,
				monthRecords: 0,
				purchaseRecords: 0,
				returnRecords: 0
			}
		}
	},

	computed: {
		// 日期选择器模式
		datePickerMode() {
			return this.dateType === 'day' ? 'date' : 'yearMonth'
		},

		// 日期选择器参数 - uView 1.x 兼容
		datePickerParams() {
			if (this.dateType === 'day') {
				return {
					value: this.selectedDate || new Date().toISOString().split('T')[0]
				}
			} else {
				// 月份选择
				const date = this.selectedDate ? new Date(this.selectedDate) : new Date()
				return {
					value: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
				}
			}
		},
		// 格式化选中日期显示
		formattedSelectedDate() {
			if (!this.selectedDate) {
				const today = new Date()
				return today.toLocaleDateString('zh-CN')
			}
			const date = new Date(this.selectedDate)
			if (this.dateType === 'day') {
				return date.toLocaleDateString('zh-CN')
			} else {
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
			}
		},
		
		// 日期选择器模式
		datePickerMode() {
			return this.dateType === 'day' ? 'date' : 'month'
		},
		
		// 统计信息
		totalPurchaseCount() {
			return this.displayList.filter(item => item.type === '采购').length
		},
		
		totalReturnCount() {
			return this.displayList.filter(item => item.type === '退货').length
		},
		
		totalPurchaseQuantity() {
			return this.displayList
				.filter(item => item.type === '采购')
				.reduce((sum, item) => sum + Math.abs(item.quantity), 0)
		},
		
		totalReturnQuantity() {
			return this.displayList
				.filter(item => item.type === '退货')
				.reduce((sum, item) => sum + Math.abs(item.quantity), 0)
		}
	},
	
	onLoad() {
		this.initPage()
	},
	
	onPullDownRefresh() {
		this.onRefresh()
	},
	
	onReachBottom() {
		this.loadMore()
	},
	
	methods: {
		// 初始化页面
		async initPage() {
			// 设置默认日期为今天
			if (!this.selectedDate) {
				this.selectedDate = new Date().toISOString().split('T')[0]
			}
			
			await this.loadData()
			await this.loadStats()
		},
		
		// 加载数据
		async loadData(type = 'refresh') {
			if (type === 'refresh') {
				this.loading = true
				this.currentPage = 1
			} else if (type === 'loadmore') {
				if (!this.hasMore || this.loadingMore) return
				this.loadingMore = true
				this.currentPage++
			}
			
			try {
				const params = {
					page: this.currentPage,
					pageSize: this.pageSize,
					keyword: this.searchKeyword,
					dateType: this.dateType,
					selectedDate: this.selectedDate
				}
				
				const response = await getMockProductFlowList(params)
				
				if (response.code === 200) {
					const { list, hasMore } = response.data
					
					if (type === 'refresh') {
						this.flowList = list
						this.displayList = list
					} else if (type === 'loadmore') {
						this.flowList = this.flowList.concat(list)
						this.displayList = this.flowList
					}
					
					this.hasMore = hasMore
				}
			} catch (error) {
				console.error('加载数据失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
				this.loadingMore = false
				this.refreshing = false
				
				if (type === 'refresh') {
					uni.stopPullDownRefresh()
				}
			}
		},
		
		// 加载统计数据
		async loadStats() {
			try {
				const response = await getMockProductFlowStats()
				if (response.code === 200) {
					this.stats = response.data
				}
			} catch (error) {
				console.error('加载统计数据失败:', error)
			}
		},
		
		// 刷新数据
		async onRefresh() {
			this.refreshing = true
			await this.loadData('refresh')
			await this.loadStats()
		},
		
		// 加载更多
		loadMore() {
			this.loadData('loadmore')
		},
		
		// 切换日期类型
		switchDateType(type) {
			if (this.dateType !== type) {
				this.dateType = type
				this.selectedDate = new Date().toISOString().split('T')[0]
				this.loadData('refresh')
			}
		},
		
		// 显示日期选择器
		showDatePickerModal() {
			this.showDatePicker = true
		},
		
		// 日期选择确认 - uView 1.x 兼容
		onDateConfirm(event) {
			let selectedValue = ''

			// 兼容不同的事件格式
			if (event && event.detail && event.detail.value) {
				selectedValue = event.detail.value
			} else if (event && event.value) {
				selectedValue = event.value
			} else if (typeof event === 'string') {
				selectedValue = event
			}

			if (selectedValue) {
				if (this.dateType === 'month') {
					// 月份选择，转换为完整日期格式
					this.selectedDate = selectedValue + '-01'
				} else {
					this.selectedDate = selectedValue
				}
				this.showDatePicker = false
				this.loadData('refresh')
			}
		},
		
		// 日期选择取消
		onDateCancel() {
			this.showDatePicker = false
		},
		
		// 搜索
		onSearch() {
			this.loadData('refresh')
		},
		
		// 清空搜索
		onSearchClear() {
			this.searchKeyword = ''
			this.loadData('refresh')
		},
		
		// 格式化数量显示
		formatQuantity(quantity) {
			if (quantity > 0) {
				return `+${quantity}`
			}
			return `${quantity}`
		},
		
		// 获取数量颜色
		getQuantityColor(quantity) {
			return quantity > 0 ? '#19be6b' : '#fa3534'
		},
		
		// 点击行事件
		handleRowClick(item) {
			console.log('点击流水记录:', item)
			// 可以跳转到详情页面或显示详情弹窗
		}
	}
}
